package shiro;

import cn.cqone.crm.domain.Employee;
import cn.cqone.crm.domain.Permission;
import cn.cqone.crm.service.EmployeeService;
import cn.cqone.crm.service.PermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class myRealm extends AuthorizingRealm {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private EmployeeService employeeService;
    private ByteSource salt = ByteSource.Util.bytes("wlt");
	
	public ByteSource getSalt() {
		return salt;
	}

	public void setSalt(ByteSource salt) {
		this.salt = salt;
	}


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection  principals) {
        System.out.println("授权方法执行了");
//       获取到employee对象
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
//        Employee employee1 = (Employee) principalCollection.getPrimaryPrincipal();
//        获得authorizationInfo对象的子类
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        通过employee的id获得一个该id的权限set集合
        List<Permission> permissionByEmployeeId = permissionService.findPermissionByEmployeeId(employee.getId());
        Set<String> permissions = new HashSet<>();
        permissionByEmployeeId.forEach(permission -> {
            permissions.add(permission.getSn());
        });
//        进行授权
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }




    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //拿到用户名
        String username = token.getUsername();
        Employee employee=employeeService.findByName(username);
        //System.out.println(employee);
        return new SimpleAuthenticationInfo(employee,employee.getPassword(),salt,"myRealm");
    }
}



